package icu.cqcai.xinsi.mapper;

import icu.cqcai.xinsi.domain.InterviewSession;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 面试会话数据访问层接口
 */
@Mapper
public interface InterviewSessionMapper {
    
    /**
     * 创建面试会话
     */
    @Insert("INSERT INTO interview_sessions (user_id, session_id, target_position, work_experience, skills, total_questions, status, create_time, update_time) " +
            "VALUES (#{userId}, #{sessionId}, #{targetPosition}, #{workExperience}, #{skills}, #{totalQuestions}, #{status}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertSession(InterviewSession session);
    
    /**
     * 根据会话ID查询会话信息
     */
    @Select("SELECT * FROM interview_sessions WHERE session_id = #{sessionId} AND status > 0")
    InterviewSession findBySessionId(@Param("sessionId") String sessionId);
    
    /**
     * 根据用户ID查询会话列表
     */
    @Select("SELECT * FROM interview_sessions WHERE user_id = #{userId} AND status > 0 ORDER BY create_time DESC")
    List<InterviewSession> findByUserId(@Param("userId") Long userId);
    
    /**
     * 根据用户ID查询已完成的面试记录
     */
    @Select("SELECT * FROM interview_sessions WHERE user_id = #{userId} AND status = 2 ORDER BY submit_time DESC")
    List<InterviewSession> findCompletedByUserId(@Param("userId") Long userId);
    
    /**
     * 根据用户ID查询所有有题目的面试记录（包括进行中和已完成的，无论是否回答）
     */
    @Select("SELECT DISTINCT s.* FROM interview_sessions s " +
            "INNER JOIN interview_answers a ON s.session_id = a.session_id " +
            "WHERE s.user_id = #{userId} AND s.status > 0 " +
            "ORDER BY s.update_time DESC")
    List<InterviewSession> findSessionsWithAnswersByUserId(@Param("userId") Long userId);
    
    /**
     * 更新会话题目数量
     */
    @Update("UPDATE interview_sessions SET total_questions = #{totalQuestions}, update_time = NOW() WHERE session_id = #{sessionId}")
    int updateTotalQuestions(@Param("sessionId") String sessionId, @Param("totalQuestions") Integer totalQuestions);
    
    /**
     * 更新已回答题目数量
     */
    @Update("UPDATE interview_sessions SET answered_questions = #{answeredQuestions}, update_time = NOW() WHERE session_id = #{sessionId}")
    int updateAnsweredQuestions(@Param("sessionId") String sessionId, @Param("answeredQuestions") Integer answeredQuestions);
    
    /**
     * 完成面试会话
     */
    @Update("UPDATE interview_sessions SET status = 2, submit_time = #{submitTime}, " +
            "total_score = #{totalScore}, position_match_rate = #{positionMatchRate}, " +
            "comprehensive_rating = #{comprehensiveRating}, update_time = NOW() " +
            "WHERE session_id = #{sessionId}")
    int completeSession(@Param("sessionId") String sessionId, 
                       @Param("submitTime") LocalDateTime submitTime,
                       @Param("totalScore") BigDecimal totalScore,
                       @Param("positionMatchRate") BigDecimal positionMatchRate,
                       @Param("comprehensiveRating") String comprehensiveRating);
    
    /**
     * 软删除会话
     */
    @Update("UPDATE interview_sessions SET status = 0, update_time = NOW() WHERE session_id = #{sessionId}")
    int deleteSession(@Param("sessionId") String sessionId);
    
    /**
     * 检查用户是否拥有此会话
     */
    @Select("SELECT COUNT(*) > 0 FROM interview_sessions WHERE user_id = #{userId} AND session_id = #{sessionId} AND status > 0")
    boolean userOwnsSession(@Param("userId") Long userId, @Param("sessionId") String sessionId);
    
    /**
     * 获取用户的活跃会话数量
     */
    @Select("SELECT COUNT(*) FROM interview_sessions WHERE user_id = #{userId} AND status = 1")
    int getActiveSessionCount(@Param("userId") Long userId);
    
    /**
     * 获取用户的总面试次数
     */
    @Select("SELECT COUNT(*) FROM interview_sessions WHERE user_id = #{userId} AND status >= 1")
    int getTotalSessionCount(@Param("userId") Long userId);

    void updateEvaluationStatus(@Param("sessionId") String sessionId, @Param("status") String status);
} 